<template>
  <view class="page-container">
    <!-- 活动列表区域 -->
    <scroll-view
      scroll-y
      class="activity-list-container"
      @scrolltolower="loadMore"
    >
      <!-- 进行中的活动 -->
      <view class="list-section" v-if="activeActivities.length > 0">
        <view class="section-header">
          <view class="section-title">已参加活动</view>
          <view class="filter-btn" @click="handleFilterClick">
            <uni-icons type="settings" size="20" color="#4CAF50"></uni-icons>
            <text>筛选</text>
          </view>
        </view>
        <view
          v-for="item in activeActivities"
          :key="item.id"
          class="activity-item"
          @click="goToDetail(item.id)"
        >
          <view class="activity-status">
            <uni-icons
              type="notification-filled"
              size="20"
              color="#4CAF50"
            ></uni-icons>
          </view>
          <view class="activity-content">
            <view class="activity-title">{{ item.title || "默认活动名" }}</view>
            <view class="activity-info">
              <view class="info-item">
                <uni-icons type="calendar" size="14" color="#666" />
                <text v-if="item.start_time === '略'">略</text>
                <!-- 开始时间 -->
                <uni-dateformat
                  v-else
                  :date="item.start_time"
                  format="yyyy-MM-dd hh:mm"
                />
              </view>
              <view class="info-item">
                <uni-icons type="calendar-filled" size="14" color="#666" />
                <text v-if="item.end_time === '略'">略</text>
                <!-- 结束时间 -->
                <uni-dateformat
                  v-else
                  :date="item.end_time"
                  format="yyyy-MM-dd hh:mm"
                />
              </view>
              <view class="info-item">
                <uni-icons type="location" size="14" color="#666"></uni-icons>
                <text>{{ item.location }}</text>
              </view>
            </view>
          </view>
          <uni-icons
            type="right"
            size="16"
            color="#999"
            @click="
              () => {
                handleClickDetail(item);
              }
            "
          />
        </view>
      </view>
      <!-- 已结束的活动 -->
      <view class="list-section expired" v-if="expiredActivities.length > 0">
        <view class="section-title">已结束活动</view>
        <view
          v-for="item in expiredActivities"
          :key="item.id"
          class="activity-item"
          @click="goToDetail(item.id)"
        >
          <view class="activity-status">
            <uni-icons type="checkbox" size="20" color="#999"></uni-icons>
          </view>
          <view class="activity-content">
            <view class="activity-title">{{ item.title }}</view>
            <view class="activity-info">
              <view class="info-item">
                <uni-icons type="calendar" size="14" color="#666" />
                <text v-if="item.start_time === '略'">略</text>
                <!-- 开始时间 -->
                <uni-dateformat
                  v-else
                  :date="item.start_time"
                  format="yyyy-MM-dd hh:mm"
                />
              </view>
              <view class="info-item">
                <uni-icons type="calendar-filled" size="14" color="#666" />
                <text v-if="item.end_time === '略'">略</text>
                <!-- 结束时间 -->
                <uni-dateformat
                  v-else
                  :date="item.end_time"
                  format="yyyy-MM-dd hh:mm"
                />
              </view>
              <view class="info-item">
                <uni-icons type="location" size="14" color="#999"></uni-icons>
                <text>{{ item.location }}</text>
              </view>
            </view>
          </view>
          <uni-icons
            type="right"
            size="16"
            color="#999"
            @click="
              () => {
                handleClickDetail(item);
              }
            "
          />
        </view>
      </view>
      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore">
        <uni-icons type="spinner-cycle" size="20" color="#666"></uni-icons>
        <text>加载中...</text>
      </view>
    </scroll-view>
    <!-- 替换为filter-panel组件 -->
    <filter-panel
      ref="filterPanel"
      :time-filters="timeFilters"
      :location-filters="locationFilters"
      @confirm="confirmFilter"
    />
  </view>
</template>
<script>
import { store as appStore } from "@/store/index.js";
import { store } from "@/uni_modules/uni-id-pages/common/store.js";
import FilterPanel from "@/components/filter-panel/filter-panel.vue"; // 新增导入filter-panel组件
const activityParticipant = uniCloud.importObject("activity-participant");

export default {
  components: {
    FilterPanel, // 注册filter-panel组件
  },
  data() {
    return {
      // 移除showFilter状态，由filter-panel组件管理
      locationFilters: [],
      currentTimeFilter: "all",
      hasMore: false,
      timeFilters: [
        { label: "全部", value: "all" },
        { label: "本周", value: "week" },
        { label: "本月", value: "month" },
        { label: "本年", value: "year" },
      ],
      currentLocationFilter: "all",
      activeActivities: [],
      expiredActivities: [],
    };
  },
  onLoad() {
    this.loadActivities();
  },
  watch: {
    userId() {
      // console.log('userId', this.userId);
      this.loadActivities();
    },
  },
  computed: {
    redirectUrl() {
      return appStore.redirectUrl || "";
    },
    userId() {
      return store.userInfo._id || "";
    },
  },
  methods: {
    /**
     * 根据筛选条件过滤活动数据
     * @param {Array} activities - 活动的数据
     * @param {string} timeRange - 时间范围(week/month/year/all)
     * @param {string} locationCode - 地区编码
     * @returns {Array} 过滤后的文章数据
     */
    filterActivities(activities, timeRange, locationCode) {
      const currentDate = new Date();
      let startDate = new Date();

      // 计算时间范围
      switch (timeRange) {
        case "week":
          startDate.setDate(currentDate.getDate() - 7);
          break;
        case "month":
          startDate.setMonth(currentDate.getMonth() - 1);
          break;
        case "year":
          startDate.setFullYear(currentDate.getFullYear() - 1);
          break;
        default:
          startDate = null;
      }

      return activities.filter((item) => {
        // 时间筛选
        const timeMatch =
          !startDate || new Date(item.start_time) >= startDate;

        // 地点筛选
        const locationMatch =
          locationCode === "all" ||
          item.region_address?.value?.includes(locationCode);

        return timeMatch && locationMatch;
      });
    },
    setRedirectUrlData(item) {
      const url = `/pages/list/detail?id=${encodeURIComponent(
        item.id
      )}&content=${encodeURIComponent(item.content)}&title=${encodeURIComponent(
        item.title
      )}`;
      appStore.redirectUrl = url;
      uni.navigateTo({
        url,
      });
    },
    handleClickDetail(item) {
      // console.log('handleClickDetail', item);
      this.setRedirectUrlData(item);

      uni.navigateTo({
        url: this.redirectUrl,
        fail: (err) => {
          console.error("页面跳转失败：", err);
          uni.showToast({
            title: "页面跳转失败",
            icon: "none",
          });
        },
      });
    },
    /**
     * 这里是未过期的活动
     * @param {*} data
     * @param {*} status 1 已发布但是未过期 2 过期
     * @return
     */
    converToActiveActivities(data, status = 1) {
      const result = data
        .filter((item) => item.activity_info[0].article_status == status)
        .map((item) => {
          const { activity_id, activity_info } = item;

          return {
            id: activity_id,
            title: activity_info[0].title || "略",
            start_time: activity_info[0].start_time || "略",
            end_time: activity_info[0].end_time || "略",
            region_address: activity_info[0].region_address || "略",
            location: activity_info[0].location_name || "略",
            content: activity_info[0].content || null,
            article_status: activity_info[0].article_status || 1,
            // participants: activity_info[0], // 参加活动的人数 这个需要根据外键去做统计
            // duration: activity_duration
          };
        });
      return result;
    },
    /**
     * 从活动数据中提取所有唯一的地区信息
     * @param {Array} activitiesData - 活动数据数组
     * @returns {Array} 去重后的地区筛选选项
     */
    extractUniqueRegions(activitiesData) {
      const regionSet = new Set();
      const result = [];

      // 添加默认选项
      result.push({ label: "全部", value: "all" });

      activitiesData.forEach((activity) => {
        const regionAddress = activity.activity_info[0]?.region_address;
        if (regionAddress && regionAddress.text && regionAddress.value) {
          const length = Math.min(
            regionAddress.text.length,
            regionAddress.value.length
          );
          for (let i = 0; i < length; i++) {
            const key = `${regionAddress.text[i]}_${regionAddress.value[i]}`;
            if (!regionSet.has(key)) {
              regionSet.add(key);
              result.push({
                label: regionAddress.text[i],
                value: regionAddress.value[i],
              });
            }
          }
        }
      });

      return result;
    },

    async loadActivities() {
      try {
        const user_id = this.userId || "";
        const res = await activityParticipant.getParticipatedActivities(
          user_id
        );

        if (res.code === 0) {
          // 保存原始数据
          this.originalActiveActivities = this.converToActiveActivities(
            res.data
          );
          this.originalExpiredActivities = this.converToActiveActivities(
            res.data,
            2
          );

          // 初始化显示数据
          this.activeActivities = [...this.originalActiveActivities];
          this.expiredActivities = [...this.originalExpiredActivities];

          this.locationFilters = this.extractUniqueRegions(res.data);

          // console.log('原始数据', res.data);
          // console.log('活动数据', this.activeActivities);
          // console.log('过期活动数据', this.expiredActivities);
          // console.log('地区筛选', this.locationFilters);
        } else {
          uni.showToast({
            title: res.message,
            icon: "none",
          });
        }
      } catch (err) {
        uni.showToast({
          title: "加载失败",
          icon: "none",
        });
      }
    },
    handleFilterClick() {
      this.$refs.filterPanel.openFilter(); // 改为调用filter-panel的方法
    },
    // 移除handleFilterChange方法，由filter-panel组件处理

    confirmFilter({ timeFilter, locationFilter }) {
      this.currentTimeFilter = timeFilter;
      this.currentLocationFilter = locationFilter;

      const allOriginalActivities = [
        ...this.originalActiveActivities,
        ...this.originalExpiredActivities,
      ];

      // console.log("allOriginalActivities", allOriginalActivities);

      const filteredActivities = this.filterActivities(
        allOriginalActivities,
        this.currentTimeFilter,
        this.currentLocationFilter
      );

      // 更新显示的活动列表
      this.activeActivities = filteredActivities.filter(
        (a) => a.article_status === 1
      );
      this.expiredActivities = filteredActivities.filter(
        (a) => a.article_status === 2
      );
    },
    loadMore() {
      // 模拟加载更多数据
      setTimeout(() => {
        this.hasMore = false;
      }, 1000);
    },
    goToDetail(id) {
      uni.navigateTo({
        url: `/pages/detail/detail?id=${id}`,
      });
    },
  },
};
</script>
<style>
page {
  height: 100%;
}

.page-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.filter-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  background: none;
  padding: 12rpx 24rpx;
  border: none;
}

.filter-btn text {
  font-size: 14px;
  color: #666666;
  margin-left: 8rpx;
}

.activity-list-container {
  flex: 1;
  overflow: auto;
}

.list-section {
  padding: 20rpx;
}

.list-section.expired > .section-title {
  margin-bottom: 20rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333333;
}

.activity-item:first {
  margin-top: 20px;
}

.activity-item {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: flex-start;
}

.activity-status {
  margin-right: 20rpx;
  padding-top: 6rpx;
}

.activity-content {
  flex: 1;
  margin-right: 20rpx;
}

.activity-title {
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  margin-bottom: 16rpx;
}

.activity-info {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.info-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666666;
}

.info-item text {
  margin-left: 8rpx;
}

.expired .activity-item {
  opacity: 0.7;
}

.expired .activity-title {
  color: #999999;
}

.load-more {
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666666;
  font-size: 14px;
}

.load-more text {
  margin-left: 12rpx;
}

.filter-popup {
  width: 600rpx;
  height: 100%;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
}

.filter-header {
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  font-size: 16px;
  font-weight: bold;
}

.filter-content {
  flex: 1;
  padding: 30rpx;
  overflow-y: auto;
}

.filter-item {
  margin-bottom: 30rpx;
}

.filter-label {
  font-size: 14px;
  color: #333333;
  margin-bottom: 20rpx;
  display: block;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.filter-option {
  padding: 12rpx 24rpx;
  border-radius: 24rpx;
  background-color: #f5f5f5;
  font-size: 14px;
  color: #666666;
}

.filter-option.active {
  background-color: #4caf50;
  color: #ffffff;
}

.filter-footer {
  padding: 30rpx;
  display: flex;
  gap: 20rpx;
}

.reset-btn {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  border-radius: 44rpx;
  background-color: #f5f5f5;
  color: #666666;
  font-size: 14px;
}

.confirm-btn {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  border-radius: 44rpx;
  background-color: #4caf50;
  color: #ffffff;
  font-size: 14px;
}
</style>
